﻿using FluentValidation;
using FluentValidationExample.Application.Customers.Commands;
using MediatR;

namespace FluentValidationExample.Application.Customers.CommandHandlers;

public class CreateCommandHandler : IRequestHandler<CreateCommand>
{
    private readonly IValidator<CreateCommand> _validator;

    public CreateCommandHandler(IValidator<CreateCommand> validator)
    {
        _validator = validator;
    }

    public async Task Handle(CreateCommand request, CancellationToken cancellationToken)
    {
        var validateResult = await _validator.ValidateAsync(request, cancellationToken);
        if (!validateResult.IsValid)
        {
            // throw new Exception(string.Join(",", validateResult.Errors));
            throw new ValidationException(validateResult.Errors);
        }

        await Task.CompletedTask;
    }
}